// pages/home/home.js
const defaultBannerInfo = [
  {
    image: 'http://img02.tooopen.com/images/20150928/tooopen_sy_143912755726.jpg',
    bookid: '1'
  },
  {
    image: 'http://img06.tooopen.com/images/20160818/tooopen_sy_175866434296.jpg',
    bookid: '2'
  },
  {
    image: 'http://img06.tooopen.com/images/20160818/tooopen_sy_175833047715.jpg',
    bookid: '3'
  }
]

const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: app.globalData.default.userInfo,
    bannerInfo: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.getStorage({
      key: 'userInfo',
      success: (res) => {
        this.setData({
          userInfo: res.data
        })
      },
      fail: (res) => {
        console.log(res)
        wx.getUserInfo({
          success: res => {
            console.log('getUserInfo Success', res)
            this.setData({
              userInfo: res.userInfo
            })
            wx.setStorage({
              key: 'userInfo',
              data: res.userInfo,
            })
          },
          fail: res => {
            console.log('getUserInfo Fail', res)
          }
        })
      }
    })

    const url = (name) => `https://api.douban.com/v2/book/user/${name}/collections`
    app
      .doGet(url('kongzhijingjie'), null)
      .then(res => {
        const bannerInfo = []
        for (let i = 0; i < Math.min(res.data.count, 5); i++) {
          bannerInfo.push({
            image: res.data.collections[i].book.images.small,
            bookid: res.data.collections[i].book.id
          })
        }
        if (bannerInfo.length > 0) {
          this.setData({
            bannerInfo
          })
        } else {
          this.setData({
            bannerInfo: defaultBannerInfo
          })
        }
      })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },

  gotoBook: function (e) {
    app.changePageWithData({
      url: '/pages/book/bookPage/bookPage'
    }, wx.navigateTo, {
        bookid: e.target.dataset.bookid
      })
  }
})